interface HealthCheck {
  name: string
  check: () => Promise<boolean>
  timeout?: number
}

interface HealthStatus {
  status: 'healthy' | 'unhealthy' | 'degraded'
  checks: Record<string, {
    status: 'pass' | 'fail'
    duration: number
    error?: string
  }>
  timestamp: string
}

class HealthChecker {
  private checks: HealthCheck[] = []

  addCheck(check: HealthCheck) {
    this.checks.push(check)
  }

  async runChecks(): Promise<HealthStatus> {
    const results: HealthStatus['checks'] = {}
    let overallStatus: HealthStatus['status'] = 'healthy'

    for (const check of this.checks) {
      const start = Date.now()
      
      try {
        const timeout = check.timeout || 5000
        const result = await Promise.race([
          check.check(),
          new Promise<boolean>((_, reject) => 
            setTimeout(() => reject(new Error('Timeout')), timeout)
          )
        ])

        results[check.name] = {
          status: result ? 'pass' : 'fail',
          duration: Date.now() - start
        }

        if (!result && overallStatus === 'healthy') {
          overallStatus = 'degraded'
        }
      } catch (error) {
        results[check.name] = {
          status: 'fail',
          duration: Date.now() - start,
          error: error instanceof Error ? error.message : 'Unknown error'
        }
        overallStatus = 'unhealthy'
      }
    }

    return {
      status: overallStatus,
      checks: results,
      timestamp: new Date().toISOString()
    }
  }
}

export const healthChecker = new HealthChecker()

// 添加基础健康检查
healthChecker.addCheck({
  name: 'memory',
  check: async () => {
    const usage = process.memoryUsage()
    const maxMemory = 512 * 1024 * 1024 // 512MB
    return usage.heapUsed < maxMemory
  }
})

healthChecker.addCheck({
  name: 'disk_space',
  check: async () => {
    // 简化的磁盘空间检查
    try {
      const { statSync } = await import('fs')
      return true // 实际实现需要检查磁盘空间
    } catch {
      return false
    }
  }
})

healthChecker.addCheck({
  name: 'plugin_system',
  check: async () => {
    // 检查插件系统是否正常
    try {
      // 检查是否有插件注册表
      if (typeof global !== 'undefined') {
        return true
      }
      return true
    } catch {
      return false
    }
  }
})

// 添加更多健康检查
healthChecker.addCheck({
  name: 'uptime',
  check: async () => {
    // 检查系统运行时间是否合理
    const uptime = process.uptime()
    return uptime > 0 && uptime < 365 * 24 * 3600 // 不超过一年
  }
})

healthChecker.addCheck({
  name: 'event_loop',
  check: async () => {
    // 检查事件循环延迟
    return new Promise((resolve) => {
      const start = Date.now()
      setImmediate(() => {
        const delay = Date.now() - start
        resolve(delay < 100) // 延迟小于100ms认为正常
      })
    })
  },
  timeout: 1000
})
